package bc

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/bc"
	bcReq "github.com/flipped-aurora/gin-vue-admin/server/model/bc/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"time"
)

type BcAgencyService struct {
}

// CreateBcAgency 创建bcAgency表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcAgencyService *BcAgencyService) CreateBcAgency(bcAgency *bc.BcAgency) (err error) {
	err = global.GVA_DB.Create(bcAgency).Error
	return err
}

// DeleteBcAgency 删除bcAgency表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcAgencyService *BcAgencyService) DeleteBcAgency(bcAgency bc.BcAgency) (err error) {
	err = global.GVA_DB.Delete(&bcAgency).Error
	return err
}

// DeleteBcAgencyByIds 批量删除bcAgency表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcAgencyService *BcAgencyService) DeleteBcAgencyByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]bc.BcAgency{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateBcAgency 更新bcAgency表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcAgencyService *BcAgencyService) UpdateBcAgency(bcAgency bc.BcAgency) (err error) {
	err = global.GVA_DB.Save(&bcAgency).Error
	return err
}

// GetBcAgency 根据id获取bcAgency表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcAgencyService *BcAgencyService) GetBcAgency(id uint) (bcAgency bc.BcAgency, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&bcAgency).Error
	return
}

func (bcAgencyService *BcAgencyService) GetBcAgencyByUser(userName string, projectId uint) (bcAgency bc.BcAgency, err error) {
	err = global.GVA_DB.Where("sys_user_name = ? and project_id =?", userName, projectId).Find(&bcAgency).Error
	return
}

// GetBcAgencyInfoList 分页获取bcAgency表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcAgencyService *BcAgencyService) GetBcAgencyInfoList(info bcReq.BcAgencySearch, setOfficeList []string) (list []bc.BcAgency, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&bc.BcAgency{})
	var bcAgencys []bc.BcAgency
	if len(setOfficeList) > 0 {
		db = db.Where("settle_office in ?", setOfficeList)
	}
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&bcAgencys).Error
	return bcAgencys, total, err
}

func (bcAgencyService *BcAgencyService) GetBcAgencyExpireList() (list []bc.BcAgency, err error) {
	// 创建db
	db := global.GVA_DB.Model(&bc.BcAgency{})
	var bcAgencys []bc.BcAgency
	// 如果有条件搜索 下方会自动创建搜索语句
	db = db.Where("created_at < ? ", time.Now().AddDate(0, 0, -7))
	err = db.Find(&bcAgencys).Error
	return bcAgencys, err
}
